package com.southminority.ethnic.config;

import com.southminority.ethnic.common.context.UserContext;
import com.southminority.ethnic.pojo.User;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.time.LocalDateTime;

/**
 * MyBatis Plus自动填充处理器
 * 用于自动设置创建时间、更新时间和用户信息
 * 
 * @author SouthMinority
 */
@Slf4j
@Component
public class MyBatisPlusMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("开始执行插入填充...");
        // 兼容 java.util.Date 与 java.time.LocalDateTime 两种时间类型
        Date nowDate = new Date();
        LocalDateTime nowLdt = LocalDateTime.now();

        // 设置创建时间
        this.strictInsertFill(metaObject, "createTime", Date.class, nowDate);
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, nowLdt);

        // 设置更新时间
        this.strictInsertFill(metaObject, "updateTime", Date.class, nowDate);
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, nowLdt);
        
        // 自动填充逻辑删除字段
        this.strictInsertFill(metaObject, "isDeleted", Integer.class, 0);
        
        // 设置创建人ID（如果当前有用户登录）
        User currentUser = UserContext.getCurrentUser();
        if (currentUser != null) {
            this.strictInsertFill(metaObject, "createBy", Long.class, currentUser.getId());
            this.strictInsertFill(metaObject, "updateBy", Long.class, currentUser.getId());
        }
        
        log.info("插入填充完成");
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("开始执行更新填充...");
        // 兼容两种时间类型
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        
        // 设置更新人ID（如果当前有用户登录）
        User currentUser = UserContext.getCurrentUser();
        if (currentUser != null) {
            this.strictUpdateFill(metaObject, "updateBy", Long.class, currentUser.getId());
        }
        
        log.info("更新填充完成");
    }
} 